package cn.itsource.filter;

import cn.itsource.feign.client.RedisFeignClient;
import cn.itsource.hrm.utils.AjaxResult;
import com.alibaba.fastjson.JSON;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class AuthCheckFilter extends ZuulFilter {
    @Autowired
    private RedisFeignClient redisFeignClient ;

    @Override
    public String filterType() {
        //类型
        return "pre";
    }

    @Override
    public int filterOrder() {
        //顺序：越小越先执行
        return 1;
    }

    @Override
    public boolean shouldFilter() {
        //true,就执行下面的run,否则就不执行run

        //1.请求上下文对象
        RequestContext currentContext = RequestContext.getCurrentContext();
        //2.获取请求对象
        HttpServletRequest request = currentContext.getRequest();
        //3.获取URL
        String requestURI = request.getRequestURI();
        //4.判断URI是否不需要做登录检查   这几个是不需要做登录检查的
        if(requestURI.contains("/login") || requestURI.contains("/register") || requestURI.contains("/swagger-ui.html")){
            return false;
        }
        return true;
    }


    @Override
    public Object run() throws ZuulException {
        //做登录检查逻辑
        //1.获取请求对象
        RequestContext currentContext = RequestContext.getCurrentContext();
        HttpServletRequest request = currentContext.getRequest();

        //2.获取请求头，因为我们的Tolen在请求头里
        String token = request.getHeader("X-Token");
        //3.如果token为空
        if(StringUtils.isBlank(token)){
            //返回下面的错误流程方法
            authCheckError(currentContext);
        }else{
            //不为空调用Redis查询Token
            AjaxResult result = redisFeignClient.get(token);
            if(!result.isSuccess() || result.getResultObj() == null){
                //不合法
                authCheckError(currentContext);
            }
        }
        //4.如何合法，放行
        return null;
    }
    //抽一个方法
    private void authCheckError(RequestContext currentContext) {
        try{
            //不合法无效token,阻止继续执行
            currentContext.setSendZuulResponse(false);
            //3.1.2返回请登录的提示信息
            AjaxResult result = AjaxResult.me().setMessage("没有登录,请先登录");

            HttpServletResponse response = currentContext.getResponse();
            //josn方式返回给浏览器
            response.setContentType("application/json;charset=utf-8");

            response.getWriter().print(JSON.toJSONString(result));
        }catch (Exception e){
            e.printStackTrace();
        }
    }

}
